package net.ssta.core.util.format;

import java.io.Reader;
import java.io.StringReader;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;


public class JavaStringFormat extends ValueObjectFormat
{
	public int getLength(Object value){return value == null ? 0 : ((String)value).length();}
	
	public byte[] getBytes(Object value)
	{
		return value == null ? new byte[0] : ((String)value).getBytes();
	}
	
	public int getInt(Object value)
	{
		return value == null ? 0 : ( new BigDecimal(( (String)value).trim() ) ).intValue();
	}
	
	public double getDouble(Object value)
	{
		return value == null ? 0 : Double.parseDouble((String) value);
	}

	public float getFloat(Object value)
	{
		return value == null ? 0 : Float.parseFloat((String) value);
	}

	public long getLong(Object value)
	{
		return value == null ? 0 : ( new BigDecimal( ((String)value).trim() ) ).longValue();
	}
	
	public String getString(Object value, String defaultValue)
	{
		return value == null ? defaultValue : (String)value;
	}
	
	public String[] getStringArray(Object value)
	{
		return new String[]{(String)value};
	}
	
	public Reader getReader(Object value)
	{ 
		return value == null ? null : new StringReader((String)value);
	}
	
	public java.util.Date getJavaUtilDate(Object value, String formatString)
	{
		java.util.Date date = null;

		if(value != null && !"".equals(value))
		{
			String s = (String)value;
			try {
				if(s.length() == 19 )//yyyy-mm-dd hh:mm:ss
				{
					date = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM).parse(s);
				}
				else if(s.length() == 10 )//yyyy-mm-dd
				{
					date = DateFormat.getDateInstance(DateFormat.MEDIUM).parse(s);
				}
				else if(s.length() == 8 )//hh:mm:ss
				{
					date = DateFormat.getTimeInstance(DateFormat.MEDIUM).parse(s);
				}
			}
			catch (ParseException e)
			{
				throw new IllegalArgumentException("the date format is incorrect : " + s);
			}
		}
		
		return date;
	}
	
	public Boolean getJavaBoolean(Object value)	{ return value == null ? Boolean.FALSE : Boolean.valueOf((String)value); }
	
	public java.sql.Date getJavaSqlDate(Object value, String formatString)
	{
		java.util.Date javaUtilDate = getJavaUtilDate( value, formatString);
		return javaUtilDate == null ? null : new java.sql.Date(javaUtilDate.getTime()); 
	}
	
	public Timestamp getJavaSqlTimestamp(Object value, String formatString)	
	{
		return value == null ? null : Timestamp.valueOf((String)value); 
	}
	
}
